package com.ygxsk.carhome.ui.rice;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventRiceTickMain;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusCarWade;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.CardMainBottomAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-26  15:28
 * @Description:饭票餐券的发放页面；分发页面
 */
public class RiceTicketOutActivity extends ErrorActivity {

    //搜索按钮 的idview
//    @BindView(R.id.textviewriceticketsearch)
//    RoundTextView textViewRiceTicketSearch;

    //选中人员之后的 人员回显；
//    @BindView(R.id.textviewinputphonechooserice)
//    TextView textViewInputPhoneChooseRice;

    //添加发送的按钮
//    @BindView(R.id.layoutbuttonriceticketplay)
//    RoundTextView layoutButtonRiceTicketPlay;

//    @BindView(R.id.editviewinputcustomerphone)
//    ClearEditText editViewInPutCustomerPhone;

    @BindView(R.id.recyclerviewincardriceticket)
    RecyclerView recyclerViewInCardRiceTicket;

    //餐券的下拉刷新操作
    @BindView(R.id.refreshlayoutinriceticketsend)
    SmartRefreshLayout refreshLayoutInRiceTicketSend;

    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    //优惠券历史记录装载
    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<>();
    //添加
    private CardMainBottomAdapter cardMainBottomAdapter;

    //这里的弹窗是 客户的信息
//    private ArrayList<EvaluateWadeInfo> mDataResources_customerPerson = new ArrayList<>();

    //弹出是 搜索出来的这个客户的 列表
//    private BasePopupView basePopupView_customerPerson;

    private RiceTickAttachPopupBg riceTickAttachPopupBg;

    //选择的这个客户的id ,用在发送 优惠券上；
    private String customerId_upLoad;

//    @OnClick({R.id.constraintlayoutheadersmartgo})
//    public void clickInRiceTicketMain(View view) {
//
//        switch (view.getId()) {

//            case R.id.textviewriceticketsearch: {//搜索按钮
//
//                KeyboardUtils.hideSoftInput(RiceTicketOutActivity.this);
//
//                method_SearchSomeThing();
//
//                break;
//            }

//            case R.id.constraintlayoutheadersmartgo: {//查看更多--也即是简单的历史记录，非核销记录
//
//                KeyboardUtils.hideSoftInput(RiceTicketOutActivity.this);
//
//                Bundle extra_bundle = new Bundle();
//                //携带是从哪个页面过去的？
//                //携带标志 是从 餐券发放过去的,因为餐券内容较少，不用太多判断。
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY);
//
//                //2024-1-3 09:51:03 新增逻辑：从餐券过来和从客户关怀的优惠券过来的不同，要注意。
//                //是否是批量审核跳转携带值内容:该处是【否】，不是批量审核过来的
//                extra_bundle.putBoolean(ExtraKey.EXTRA_ISCHECKED_MORE_ITEMS_FLAG, false);
//
//                ActivityUtils.startActivity(extra_bundle, CardSumHistoryActivity.class);
//
//                break;
//            }

//            case R.id.layoutbuttonriceticketplay: {//发放按钮--餐券的发送和提交
//
//                KeyboardUtils.hideSoftInput(RiceTicketOutActivity.this);
//
//                //校验用户的选中
//                if (TextUtils.isEmpty(customerId_upLoad)) {
//                    CommUtils.checkDialog(mAlertView);
//                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_customer_person_upload), true);
//                    mAlertView.show();
//                    return;
//                }
//
//                CommUtils.checkDialog(mAlertView);
//                mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
//                        StringUtils.getString(R.string.alert_message_card_coupon),//提示内容:确定发送吗？
//                        StringUtils.getString(R.string.clearcachecancel), //取消
//                        new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
//                        null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
//                    @Override
//                    public void onItemClick(Object o, int position) {
//
//                        if (position != AlertView.CANCELPOSITION) {
//                            method_gainAddSubmitInfo_upLoad();
//                        }
//                    }
//                });
//
//                mAlertView.setCancelable(true);
//                mAlertView.show();
//
//                break;
//            }

//            default:
//                break;
//        }

//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        if (mDataResources == null) {
            mDataResources = new ArrayList<>();
        }

        initloading();

        initViews();

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_rice_ticket_out_activity;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_rice_card));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

        //右侧是一个加号布局
        //2024-1-10 14:00:58新增的特殊图片
        toolbarHelper.setImageViewRight(true, R.drawable.icon_rigad, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                new XPopup.Builder(mActivityInstance)
//                        .hasShadowBg(false)
//                        .isTouchThrough(true)
//                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
////                        .atView(toolbarHelper.getImageViewRight())
////                        .atView(toolbarHelper.getToolbar().findViewById(R.id.imageviewinphone))
//                        .atView(imageViewRight)
//                        .isCenterHorizontal(true)
//                        .hasShadowBg(false) // 去掉半透明背景
//                        .asCustom(new RightBubbleAttachPopup(mActivityInstance))
//                        .show();

//                showPop();
//                toggleBright();

//                CustomAttachPopupBg customAttach2 = (CustomAttachPopupBg) new XPopup.Builder(mActivityInstance)
//                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
//                        .atView(v)
//                        .hasShadowBg(true)//是否展示背景
//                        .asCustom(new CustomAttachPopupBg(mActivityInstance))
//                        .show();

                riceTickAttachPopupBg = (RiceTickAttachPopupBg) new XPopup.Builder(mActivityInstance)
                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                        .atView(v)
                        .hasShadowBg(true)
                        .asCustom(new RiceTickAttachPopupBg(mActivityInstance, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                            }
                        }))
                        .show();

            }
        });


        //右侧是【编辑】
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_cardverifi_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//
//                //携带是 餐券 到卡券核销 列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY);
//
//                ActivityUtils.startActivity(extra_bundle, CardDistHistoryActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initViews() {

        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusCarWade.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusCarWade>() {

                    @Override
                    public void accept(RxBusCarWade rxBusCarWade) throws Throwable {

                        if (rxBusCarWade != null) {

                            if (rxBusCarWade.getActionFlag() == ExtraValue.MODIFY_EVALUATE_RICE_TICKET_PERSON_SELECT) {//【选择卡券发放的那个人】；

                                //搜索出这个被发放人员的
                                customerId_upLoad = rxBusCarWade.getEvaluateWadeInfo().getDictCode();

                                //修改文本
//                                if (textViewInputPhoneChooseRice != null) {
//                                    textViewInputPhoneChooseRice.setText(rxBusCarWade.getEvaluateWadeInfo().getDictLabel());
//                                }

                            }
                        }
                    }
                }));

        //布局的适配器填充，下拉刷新等等；
        recyclerViewInCardRiceTicket.setLayoutManager(new MyLinearLayoutManager(this));
        //卡券使用的是一个适配器
        cardMainBottomAdapter = new CardMainBottomAdapter(flag_jumpfrom_where, R.layout.smartgolistadapter, mDataResources);
        recyclerViewInCardRiceTicket.setAdapter(cardMainBottomAdapter);
        cardMainBottomAdapter.notifyDataSetChanged();

        cardMainBottomAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                // TODO: 2023-07-13 15:07 跳转到这个客户的详情页面
//                Bundle extra_bundle = new Bundle();
//                SmartGoOutItemBean smartGoOutItemBean = smartGoItemAdapter.getItem(position);
//              extra_bundle.putParcelable(ExtraKey.EXTRA_RUNMANGROUPMANAGEBEAN, runManGroupManageBeanItem);

                //判断 状态，如果是【待认证】的，那么就【添加认证】；
//                int currentState = smartGoOutItemBean.getStateItem();

            }
        });

        //R.id.textvieweditviewphonecarsmart
        cardMainBottomAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                if (couponCustomerVo != null) {
                    clickButton_toCallPhone(RiceTicketOutActivity.this, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_8.getIndex());
                }

            }
        });

        //下拉刷新操作
        if (refreshLayoutInRiceTicketSend != null) {

            refreshLayoutInRiceTicketSend.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            getServerDatasCardHistory();

                            refreshLayout.finishLoadMore();

                        }
                    });

                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

//                            getServerDatasCardHistory();
                            gainDatas();

                            refreshLayout.finishRefresh();

                        }
                    });

                }
            });

        }


    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            pagination_upLoad = Parameterkey.pageNum_default_first;//重置

            if (mDataResources != null && !mDataResources.isEmpty()) {
                mDataResources.clear();
            }

            if (cardMainBottomAdapter != null) {
                cardMainBottomAdapter.notifyDataSetChanged();
            }

            getServerDatasCardHistory();

        } else {

            ToastUtils.showShort(StringUtils.getString(R.string.http_exception_network));

        }
    }


    //获取的优惠券的历史：历史记录--这个员工发放过的 优惠券 有张三-李四-王五的；
    private void getServerDatasCardHistory() {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEFORMEMBERRICETICK_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageForMemberRiceTick_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponListPageForMemberRiceTick(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RiceTicketOutActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        // : 2023-08-15 14:32 这里还有更好的处理办法，使用BRAV自己的遮盖

//                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardRiceTicket);
//                        }

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            setEnableLoadmore(refreshLayoutInRiceTicketSend, false);

                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        }


                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        if (refreshLayoutInRiceTicketSend.getState() == RefreshState.Refreshing) {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "目前正处于 下拉刷新状态，所以展示  加载更多");
                            method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                        }

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInRiceTicketSend, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //因为有加载更多，这块不能要
//                        if (mDataResources != null && !mDataResources.isEmpty()) {
//                            mDataResources.clear();
//                        }

                        if (couponCustomerVoOutSide != null) {

                            ArrayList<CouponCustomerVo> couponCustomerVos = couponCustomerVoOutSide.getDataList();

                            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {

                                if (mDataResources != null) {
                                    mDataResources.addAll(couponCustomerVos);
                                }

                            }

                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardRiceTicket);
                            setEnableLoadmore(refreshLayoutInRiceTicketSend, false);
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (cardMainBottomAdapter != null) {
                            cardMainBottomAdapter.notifyDataSetChanged();
                        }

                        pagination_upLoad = couponCustomerVoOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInRiceTicketSend, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInRiceTicketSend, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInRiceTicket(EventRiceTickMain eventRiceTickMain) {

        if (eventRiceTickMain != null) {

            if (eventRiceTickMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_RICE_TICKED_MAIN_LIST) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "收到刷新主页列表的消息--EVENTBUS_EVENT_TO_REFRESH_RICE_TICKED_MAIN_LIST");

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardMainBottomAdapter != null) {
                    cardMainBottomAdapter.notifyDataSetChanged();
                }

                getServerDatasCardHistory();

            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardMainBottomAdapter != null) {
            cardMainBottomAdapter.notifyDataSetChanged();
            cardMainBottomAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        if (riceTickAttachPopupBg != null) {

            if (riceTickAttachPopupBg.isShow()) {
                riceTickAttachPopupBg.onDismiss();
            }

            riceTickAttachPopupBg.onDestroy();
            riceTickAttachPopupBg = null;
        }

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }
}